package csd.wyaiyr.com.controller;




import csd.wyaiyr.com.config.BaseResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;


@RequestMapping("/upload")
@RestController
@Slf4j
@Tag(name = "上传模块")
public class UpLoadController {

    @Value("${cardImg.targetPath}")
    private String targetPath;

    @Value("${cardImg.targetImgUrl}")
    private String targetImgUrl;


    //本地服务器上传
    @SneakyThrows
    @PostMapping("/upload")
    @Operation(summary = "上传")
    public BaseResult handleFileUpload(@RequestParam("file") MultipartFile file) {
        if(file.isEmpty()){
            return BaseResult.error("文件为空，请选择文件上传") ;
        }

        //定义存储目录
        try {
            //获取源文件名
            String random = UUID.randomUUID().toString().replaceAll("\\-", "").substring(8);
            String fileName = random+file.getOriginalFilename();
            log.info("原文件名fileName={}",fileName);
            File targetFile = new File(targetPath+fileName);

            //判断文件父目录是否存在
            if(!targetFile.getParentFile().exists()){
                //不存在就创建一个
                targetFile.getParentFile().mkdir();
            }

            //实现文件上传
            file.transferTo(targetFile);
            String imgUrl = targetImgUrl + fileName ;
            HashMap<String,String> map = new HashMap<>();
            map.put("imgUrl",imgUrl);
            log.info("文件上传成功>>>>>> url = {}" , imgUrl);
            return BaseResult.ok(map);
        } catch (IOException e) {
            log.error("文件上传异常：{}",e.getMessage());
            throw new RuntimeException(e);
        }
    }

}
